(function($) {
  var methods = {
    root : {
      title: 'Tree',
      data: [{
        'First Branch': [{ 
          '1.1': true
        }]
      },{
        'Sconde Branch': [{ 
          '2.1':[{ 
            '2.1.1': { '2.1.1.1':true, '2.1.1.2':true}
          },{
            '2.1.2': true
          }]
        },{
          '2.2':  true
        }]
      },{
        'Third Child': true
      }]
    },
    init : function( options ) { 
      return this.each(function(){
        var  it = $(this),
              defaults = methods.root,
              data =  it.data('SLMNtree');
        if (!data) {
          var settings = $.extend({}, defaults, options);
          it.addClass('SLMNtree').text(settings.title);
          methods.loopIt(settings.data,it);
          it.data('SLMNtree', {
            target :  it,
            root : settings
          });
        }
      });        
    },
    loopIt : function(obj, target){
      for (var key in obj)
      {
          if (!obj.hasOwnProperty(key)){
            continue;       // skip this property
          }
          if (obj[key] instanceof Array) {
            target.append($('<ul><a href="#"><ins>&nbsp;</ins>' + key + '</a></ul>'));
            methods.loopIt(obj[key], $('ul',target).last());
            $('ul > *',target).last().addClass('SLMNtree-last');
          } else if (typeof obj[key] == 'object') {
            target.append($('<li><a href="#"><ins>&nbsp;</ins>' + key + '</a></li>'));
            methods.loopIt(obj[key], target);
            $('li',target).last().addClass('SLMNtree-last');
          } else {
            target.append($('<li><a href="#"><ins>&nbsp;</ins>' + key + '</a></li>'));
          }
      }
    },
    destroy : function( ) {
       return this.each(function(){
         var  it = $(this),
             data =  it.data('DAS');
         //$(window).unbind('.DAS');
         data.das.remove();
          it.removeData('DAS');
       })
    },
    saveData: function(){
    var filepath = document.location.href; // Get the current file
    filepath = $.twFile.convertUriToLocalPath(filepath); // Convert the path to a readable format
    var text = $.twFile.load(filepath);
    DASData = '{"position" : [' + $.map($('input:checkbox:checked',this), function(a){return '"' + $(a).attr('position') + '"'}).join(',') +']}';
    var attrs = $.parseJSON(DASData);
    var count = 0;
    for ( var i in attrs.position){
      if ($.inArray(attrs.position[i], methods.nonAttr) === -1){
        count++;
      }
    }
    $('#TotalAttributes').text('Total # of Attibutes Selected: ' + count);
    text = text.replace(/(\s+<div id="DASData" style="display:none">)(?!<\/div>)(.*)(<\/div>?)/, '$1' + DASData +'$3');
    //alert(DASData);
    var io = $.twFile.save(filepath, text,undefined, 2); 
    if (io!==true) {alert('Error can not save file.')} else {alert('File saved successfully.')};
  },
  loadData: function(){
    DASData = $.parseJSON(this.text());
      /*$.each(DASData.position, function(i,v){
        $('#DASdiv input:checkbox:not(:disabled):not(:checked)[position="'+v+'"]').prop({checked:true});
      });*/
    var count = 0;
    for ( var i in DASData.position){
      if ($.inArray(DASData.position[i], methods.nonAttr) === -1){
        count++;
      }
    }
    $('#TotalAttributes').text('Total # of Attibutes Selected: ' + count);
    if (count > 0) {
      $('#DASRequired').prop({checked:true});
      $('#DASdiv').show();
    }
    $('#DASdiv input:checkbox:not(:disabled):not(:checked)').each(function(){
      if ($.inArray($(this).attr('position'), DASData.position) !== -1){
        $(this).prop({checked:true});
      }
    });
  },
  };
$.fn.SLMNtree = function( method ) {
  if ( methods[method] ) {
    return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
  } else if ( typeof method === 'object' || !method ) {
    return methods.init.apply( this, arguments );
  } else {
    $.error( 'Method ' +  method + ' does not exist on jQuery.das' );
  }    
};
})(jQuery);